package ntd.util.frame.javacv;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.c.opt.ComOpt;
import com.ToolOpt;
import ntd.util.UtilThreadPool;
import ntd.util.cache.FactoryCache;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.action.bean.AIServerDo;
import ntd.util.frame.javacv.bo.CameraBO;
import ntd.util.frame.javacv.remote.AiVisionRemote;
import com.tool.ToolRemote;

import java.sql.SQLException;
import java.util.List;

/**
 * AI 视觉能力
 */
public class ComVisionApi {

    
    public static List<AiVisionRemote> initAiRemote() {
        List<AiVisionRemote> aiVisionRemotes = FactoryCache.cache("aiVisionRemoteCache", 30000).cache(() -> {
            Db db = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));
            List<AIServerDo> aiServerDoList = db.findAll(Entity.create("ai_server"), AIServerDo.class);
            return CollStreamUtil.toList(aiServerDoList, AiVisionRemote::new);
        });
        return CollectionUtil.newArrayList(aiVisionRemotes);
    }

    public static List<CameraBO> initCameraList() {
        List<CameraBO> cameraBOList = FactoryCache.cache("cameraBOList", 30000).cache(() -> {
            ComOpt<Object> comOpt = ToolOpt.get("things_device_config");

            List<Entity> deviceConfigList = comOpt.list(comOpt.query());

            return CollStreamUtil.toList(deviceConfigList, CameraBO::transform);
        });
        return CollectionUtil.newArrayList(cameraBOList);
    }

    public static List<AiVisionRemote> analysisRemoteList() {
        List<AiVisionRemote> aiVisionRemotes = initAiRemote();
        CollectionUtil.filter(aiVisionRemotes, aiVisionRemote -> ToolRemote.telnetPort(aiVisionRemote.aiServerDo.getUri(), aiVisionRemote.aiServerDo.getAnalysisPort()));
        return aiVisionRemotes;
    }

    public static void main(String[] args) throws SQLException {
        StaticLog.info(JSONUtil.toJsonStr(analysisRemoteList()));
//        UtilThreadPool.periodRun(() -> {
//            String cache = FactoryCache.cache("aiVisionRemoteCache", 5000).cache(() -> {
//                StaticLog.info("缓存过期");
//                return "123";
//            });
//            StaticLog.info(cache);
//        }, 2);
    }
}
